package com.huanghuai.retail.utils;

import com.huanghuai.retail.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class VerifyUtils {
    public static String verify(Class<?> clazz, Object target) {
        Errors errors = new BeanPropertyBindingResult(target,
                target.getClass().getSimpleName());
        try {
            ValidationUtils.invokeValidator(
                    (Validator) clazz.newInstance(),
                    target, errors);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        if (errors.hasErrors()) {
            List<ObjectError> allErrors = errors.getAllErrors();
            for (ObjectError error : allErrors) {
                return error.getDefaultMessage();
            }
        }
        return "";
    }



//    校验的工具类封装 获取错误信息并且返回
    static public R<Object> getValidateError(BindingResult bindingResult) {

        if (!bindingResult.hasErrors()) {
            return null;
        }

        Map<String, String> fieldErrors = new HashMap<>();

        for (FieldError error : bindingResult.getFieldErrors()) {
            fieldErrors.put(error.getField(), error.getCode() + " | " + error.getDefaultMessage());
        }

        HashMap<String, Object> result = new HashMap<>();
        result.put("fieldErrors", fieldErrors);
        int value = HttpStatus.UNPROCESSABLE_ENTITY.value();
        return R.error(value+":参数错误"+result);

    }

}
